"""
应用状态管理器

负责集中管理应用中的所有状态，确保状态更新的一致性。
实现了观察者模式，允许UI组件监听状态变化并作出响应。
"""
import time
import threading
from typing import Dict, List, Any, Optional, Callable, Tuple, Union

from app.state.state_types import StateType, StateValues, StateOptions
from app.utils.logger import Logger


class AppStateManager:
    """
    应用状态管理器
    
    集中管理应用所有状态，提供状态更新、获取和监听机制。
    确保状态更新的一致性和可靠性。
    """
    
    # 单例实例
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        """确保单例模式"""
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(AppStateManager, cls).__new__(cls)
                cls._instance._initialized = False
            return cls._instance
    
    def __init__(self):
        """初始化状态管理器"""
        # 如果已经初始化，则不再重复初始化
        if getattr(self, '_initialized', False):
            return
            
        # 获取日志记录器
        self.logger = Logger.get_logger("app_state_manager")
        self.logger.info("初始化应用状态管理器")
        
        # 状态存储
        self._states: Dict[StateType, Dict[str, Any]] = {}
        
        # 状态监听器
        self._listeners: Dict[StateType, List[Callable[[StateType, str, str], None]]] = {}
        
        # 状态历史记录
        self._history: Dict[StateType, List[Tuple[str, float]]] = {}
        
        # 最大历史记录条数
        self._max_history = 20
        
        # 初始化所有状态
        for state_type in StateType:
            self._states[state_type] = {
                "value": StateOptions.get_default(state_type),
                "last_update": time.time(),
                "active": True,
                "source": "init",
                "overridden_by": None
            }
            self._listeners[state_type] = []
            self._history[state_type] = []
        
        self._initialized = True
        self.logger.info("应用状态管理器初始化完成")
    
    def set_state(self, state_type: Union[StateType, str], value: str, source: str = None) -> bool:
        """
        设置状态值
        
        @param state_type: 状态类型，可以是StateType枚举或字符串
        @param value: 状态值
        @param source: 状态来源，用于日志记录
        @return: 是否成功设置
        """
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                self.logger.error(f"未知的状态类型: {state_type}")
                return False
        
        # 验证状态是否存在
        if state_type not in self._states:
            self.logger.error(f"尝试设置未定义的状态类型: {state_type}")
            return False
            
        # 验证状态值是否合法
        if not StateOptions.is_valid_value(state_type, value):
            self.logger.warning(f"状态值不合法: {state_type} = {value}, 已忽略")
            return False
        
        # 检查此状态是否被高优先级状态覆盖
        for other_type, state in self._states.items():
            # 如果存在overridden_by且不为None，则此状态当前被覆盖
            if state_type.value in StateOptions.get_overrides(other_type) and state.get("active", False):
                # 记录状态但不通知UI更新
                old_value = self._states[state_type]["value"]
                self._states[state_type]["value"] = value
                self._states[state_type]["last_update"] = time.time()
                self._states[state_type]["source"] = source
                self._states[state_type]["overridden_by"] = other_type
                
                # 添加到历史记录
                self._add_to_history(state_type, value)
                
                self.logger.debug(f"状态 {state_type} 被 {other_type} 覆盖，更新值但不通知UI: {old_value} -> {value}")
                return True
                
        # 记录之前的值用于对比
        old_value = self._states[state_type]["value"]
        
        # 如果值没变化，不需要更新
        if old_value == value:
            return True
        
        # 更新状态
        self._states[state_type]["value"] = value
        self._states[state_type]["last_update"] = time.time()
        self._states[state_type]["active"] = True
        self._states[state_type]["source"] = source
        self._states[state_type]["overridden_by"] = None
        
        # 添加到历史记录
        self._add_to_history(state_type, value)
        
        # 此状态会覆盖其他状态
        overrides = StateOptions.get_overrides(state_type)
        for override_type in overrides:
            if override_type in self._states:
                self._states[override_type]["overridden_by"] = state_type
                self.logger.debug(f"状态 {state_type} 覆盖了 {override_type}")
        
        # 通知状态变化
        self._notify_state_change(state_type, value, old_value)
        
        self.logger.debug(f"状态已更新: {state_type} = {value}")
        return True
    
    def get_state(self, state_type: Union[StateType, str]) -> str:
        """
        获取状态值
        
        @param state_type: 状态类型
        @return: 状态值
        """
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                self.logger.error(f"获取未知的状态类型: {state_type}")
                return ""
        
        if state_type not in self._states:
            return ""
            
        return self._states[state_type]["value"]
    
    def get_state_info(self, state_type: Union[StateType, str]) -> Dict[str, Any]:
        """
        获取状态的完整信息
        
        @param state_type: 状态类型
        @return: 状态信息字典
        """
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                return {}
        
        if state_type not in self._states:
            return {}
            
        return self._states[state_type].copy()
    
    def get_all_states(self) -> Dict[StateType, str]:
        """
        获取所有状态的当前值
        
        @return: 状态类型到状态值的映射
        """
        return {state_type: state["value"] for state_type, state in self._states.items()}
    
    def add_listener(self, state_type: Union[StateType, str], listener: Callable[[StateType, str, str], None]) -> bool:
        """
        添加状态变化监听器
        
        @param state_type: 状态类型
        @param listener: 监听器回调函数，接收参数：状态类型、新值、旧值
        @return: 是否成功添加
        """
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                self.logger.error(f"尝试为未知状态类型添加监听器: {state_type}")
                return False
        
        if state_type not in self._listeners:
            self._listeners[state_type] = []
            
        if listener not in self._listeners[state_type]:
            self._listeners[state_type].append(listener)
            self.logger.debug(f"已添加状态监听器: {state_type}")
            return True
            
        return False
    
    def remove_listener(self, state_type: Union[StateType, str], listener: Callable[[StateType, str, str], None]) -> bool:
        """
        移除状态变化监听器
        
        @param state_type: 状态类型
        @param listener: 监听器回调函数
        @return: 是否成功移除
        """
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                return False
        
        if state_type in self._listeners and listener in self._listeners[state_type]:
            self._listeners[state_type].remove(listener)
            self.logger.debug(f"已移除状态监听器: {state_type}")
            return True
            
        return False
    
    def get_state_history(self, state_type: Union[StateType, str], limit: int = 10) -> List[Tuple[str, float]]:
        """
        获取状态历史记录
        
        @param state_type: 状态类型
        @param limit: 最大记录条数
        @return: 状态值和时间戳的元组列表
        """
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                return []
        
        if state_type not in self._history:
            return []
            
        # 返回指定数量的最新历史记录，时间戳倒序排列
        history = sorted(self._history[state_type], key=lambda x: x[1], reverse=True)
        return history[:limit]
    
    def clear_state_history(self, state_type: Optional[Union[StateType, str]] = None) -> None:
        """
        清除状态历史记录
        
        @param state_type: 要清除的状态类型，如果为None则清除所有历史
        """
        if state_type is None:
            # 清除所有历史
            for state_type in StateType:
                self._history[state_type] = []
            self.logger.debug("已清除所有状态历史记录")
            return
            
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                return
        
        if state_type in self._history:
            self._history[state_type] = []
            self.logger.debug(f"已清除状态历史记录: {state_type}")
    
    def reset_state(self, state_type: Optional[Union[StateType, str]] = None) -> None:
        """
        重置状态为默认值
        
        @param state_type: 要重置的状态类型，如果为None则重置所有状态
        """
        if state_type is None:
            # 重置所有状态
            for state_type in StateType:
                old_value = self._states[state_type]["value"]
                default_value = StateOptions.get_default(state_type)
                self._states[state_type] = {
                    "value": default_value,
                    "last_update": time.time(),
                    "active": True,
                    "source": "reset",
                    "overridden_by": None
                }
                self._notify_state_change(state_type, default_value, old_value)
            self.logger.debug("已重置所有状态为默认值")
            return
            
        # 转换字符串状态类型为枚举
        if isinstance(state_type, str):
            try:
                state_type = StateType(state_type)
            except ValueError:
                return
        
        if state_type in self._states:
            old_value = self._states[state_type]["value"]
            default_value = StateOptions.get_default(state_type)
            self._states[state_type] = {
                "value": default_value,
                "last_update": time.time(),
                "active": True,
                "source": "reset",
                "overridden_by": None
            }
            self._notify_state_change(state_type, default_value, old_value)
            self.logger.debug(f"已重置状态为默认值: {state_type} = {default_value}")
    
    def _notify_state_change(self, state_type: StateType, new_value: str, old_value: str) -> None:
        """
        通知状态变化
        
        @param state_type: 状态类型
        @param new_value: 新状态值
        @param old_value: 旧状态值
        """
        if state_type in self._listeners:
            for listener in self._listeners[state_type]:
                try:
                    listener(state_type, new_value, old_value)
                except Exception as e:
                    self.logger.error(f"状态监听器调用异常: {e}")
                    
        # 检查这个状态变化是否需要恢复之前被覆盖的状态
        # 例如：播放状态从"播放中"变为"就绪"时，应该恢复显示AI服务状态
        if state_type == StateType.PLAYBACK and new_value == StateValues.READY and old_value.startswith(StateValues.PLAYING):
            # 播放结束时，检查是否有被覆盖的状态需要恢复
            overrides = StateOptions.get_overrides(state_type)
            for override_type in overrides:
                if override_type in self._states and self._states[override_type]["overridden_by"] == state_type:
                    # 清除overridden_by标记
                    self._states[override_type]["overridden_by"] = None
                    # 通知状态变化，使UI刷新
                    self._notify_state_change(
                        override_type, 
                        self._states[override_type]["value"], 
                        self._states[override_type]["value"]
                    )
                    self.logger.debug(f"播放结束，恢复显示状态: {override_type} = {self._states[override_type]['value']}")
    
    def _add_to_history(self, state_type: StateType, value: str) -> None:
        """
        添加状态值到历史记录
        
        @param state_type: 状态类型
        @param value: 状态值
        """
        if state_type not in self._history:
            self._history[state_type] = []
            
        # 添加当前时间戳
        self._history[state_type].append((value, time.time()))
        
        # 限制历史记录数量
        if len(self._history[state_type]) > self._max_history:
            self._history[state_type] = self._history[state_type][-self._max_history:] 